package com.mydemo.springlearning.functions.contextlistener;

import com.mydemo.springlearning.functions.CRUDdemo.entity.User;
import com.mydemo.springlearning.functions.CRUDdemo.byxml.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.List;

/**
 * @author hd
 * @date 2022/2/8 16:29
 */
@WebListener
@Slf4j
public class listenerOnRedis implements ServletContextListener {
    @Resource
    private RedisTemplate<String, User> redisTemplate;
    public static final String ALL_USER = "ALL_USER_LIST";

    @Autowired
    private UserService userService;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        final List<User> userList = userService.getAllUsers();
        redisTemplate.delete(ALL_USER);
        redisTemplate.opsForList().leftPushAll(ALL_USER, userList);
        final List<User> users = redisTemplate.opsForList().range(ALL_USER, 0, -1);
        log.debug("缓存中有用户数量:{}人",users!=null?users.size():0);
        log.warn("ServletContextEvent初始化完毕！");
        ServletContextListener.super.contextInitialized(sce);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        log.warn("ServletContextEvent销毁！");
        ServletContextListener.super.contextDestroyed(sce);
    }
}
